import AMapLoader from "@amap/amap-jsapi-loader"

let init = true
const loading = ref(true)
const AMapRef = shallowRef(null)
const mapRefExport = ref(null)

enum markerType {
  WATER = "water",
  AIR = "air",
  MANAGE = "manage"
}
// export const markerType = {
//   WATER:'water',
//   AIR:'air',
//   MANAGE:"manage"
// }
let mapRef = null
let AMap = null

const markerListObj = {}

export const useMap = (id) => {
  if (!init) return

  const getDistrictMask = () => {
    const opts = {
      subdistrict: 1,
      level: "province",
      extensions: "all",
      showbiz: false
    }
    const district = new AMap.DistrictSearch(opts)
    district.search("成都市", function (status, result) {
      const bounds = result.districtList[0]["boundaries"]
      const childrenDistrict = result.districtList[0].districtList
      const mask = []
      for (let i = 0; i < bounds.length; i++) {
        mask.push([bounds[i]])
      }
      //实例化地图
      mapRefExport.value = mapRef = new AMap.Map(id, {
        mask: mask,
        zoom: 11, //设置当前显示级别
        expandZoomRange: true, //开启显示范围设置
        zooms: [7, 20], //最小显示级别为7，最大显示级别为20
        center: [104.07, 30.57],
        viewMode: "3D", //这里特别注意，设置为3D则其它地区不显示
        zoomEnable: true, //是否可以缩放地图
        resizeEnable: true,
        mapStyle: "amap://styles/darkblue"
      })

      //添加描边
      const mapBorder = new AMap.Polyline({
        path: bounds,
        strokeColor: "#3078AC",
        strokeWeight: 2
      })

      mapRef.on("complete", () => {
        loading.value = false

        setTimeout(() => {
          nextTick(() => {
            // mapRef.add(mapBorder)
          })
        }, 3000)

        childrenDistrict.forEach((item) => {
          district.search(item.adcode, (childStatus, childResult) => {
            const childBounds = childResult.districtList[0]["boundaries"]
            for (let i = 0; i < childBounds.length; i++) {
              new AMap.Polyline({
                path: childBounds[i],
                strokeColor: "rgba(34, 80, 114,0.1)",
                strokeWeight: 1,
                map: mapRef
              })
            }
          })
        })

        setTimeout(() => {
          for (let i = 0; i < bounds.length; i++) {
            new AMap.Polyline({
              path: bounds[i],
              strokeColor: "#3078AC",
              strokeWeight: 2,
              map: mapRef
            })
          }
        }, 5000)

        addMarkerManage()
        addMarkerAir()
        addMarkerWater()

        addCircle()
        addPolygon()
      })
    })
  }
  const addMarkerManage = () => {
    addMarker(markerType.MANAGE, "default", [104.07, 30.57])

    // markerListObj[markerType.MANAGE].setContent(markerContent)
    // markerListObj[markerType.MANAGE].setMap(mapRef)
  }
  const addMarkerAir = () => {
    addMarker(markerType.AIR, "red", [104.17, 30.57])
  }
  const addMarkerWater = () => {
    addMarker(markerType.WATER, "red", [104.14, 30.44])
  }
  const addMarker = (
    id: string,
    icon: string,
    position: Array<number>,
    clear?: boolean,
    zooms?: number[]
  ) => {
    let dotClass = "marker-dot-default"

    zooms = zooms || [8, 18]
    if (icon === "red") {
      icon =
        "//a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-red.png"
      dotClass = "marker-dot-red"
    } else if (icon === "default") {
      icon =
        "//a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-default.png"
    }
    if (clear) clearMaker()

    const markerContent = `
    <div>
      <img src='${icon}'>
      <span class="${dotClass} marker-animate"></span>
      <span class="${dotClass} marker-animate-delay"></span>
    </div>
    `

    markerListObj[id] = new AMap.Marker({
      map: mapRef,
      icon,
      position,
      zooms,
      content: markerContent
    })

    // markerListObj[id].setContent(markerContent)
  }
  const clearMaker = () => {
    for (const i in markerListObj) {
      markerListObj[i]?.setMap(null)
    }
  }
  const changeMaker = (type) => {
    clearMaker()
    switch (type) {
      case markerType.AIR:
        addMarkerAir()
        break
      case markerType.WATER:
        addMarkerWater()
        break
      case markerType.MANAGE:
        addMarkerManage()
        break
      default:
        break
    }
  }
  const addCircle = () => {
    const circle = new AMap.Circle({
      center: [104.043246, 30.641849],
      radius: 1000, //半径
      borderWeight: 3,
      strokeColor: "#FF33FF",
      strokeOpacity: 0.2,
      strokeWeight: 6,
      fillOpacity: 0.4,
      strokeStyle: "dashed",
      strokeDasharray: [10, 10],
      // 线样式还支持 'dashed'
      fillColor: "#1791fc",
      zIndex: 50
    })

    circle.setMap(mapRef)
  }

  const addPolygon = () => {
    const path = [
      new AMap.LngLat(103.673025, 30.630183), // 崇州
      new AMap.LngLat(103.92342, 30.574884), // 双流
      new AMap.LngLat(103.810906, 30.410404) // 新津
    ]

    const polygon = new AMap.Polygon({
      path: path,
      fillColor: "#5b9dd8", // 多边形填充颜色
      borderWeight: 2, // 线条宽度，默认为 1
      strokeColor: "#1791fc" // 线条颜色
    })

    mapRef.add(polygon)
  }

  onMounted(async () => {
    if (!init) return
    init = false

    window._AMapSecurityConfig = {
      securityJsCode: "b9fad02a4571cc7de163474cfe4060e8"
    }
    AMap = await AMapLoader.load({
      key: "650effa99e2c62e94cfa32731bc9a213", // 申请好的Web端开发者Key，首次调用 load 时必填
      version: "1.4.14", // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
      plugins: [
        "AMap.ToolBar",
        "AMap.Scale",
        "AMap.MapType",
        "AMap.Geolocation",
        "AMap.Weather",
        "AMap.MarkerClusterer",
        "AMap.DistrictSearch",
        "AMap.DistrictLayer"
      ] // 需要使用的的插件列表，如比例尺'AMap.Scale'等
    })
    AMapRef.value = AMap
    getDistrictMask()
  })

  return {
    AMapRef,
    mapRef: mapRefExport,
    loading,
    changeMaker,
    markerType,
    addMarker
  }
}
